package cn.stylefeng.guns.sys.modular.auth.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.consts.CommonConstant;
import cn.stylefeng.guns.core.util.HttpServletUtil;
import cn.stylefeng.guns.core.util.IpAddressUtil;
import cn.stylefeng.guns.sys.core.cache.RedisBackCache;
import cn.stylefeng.guns.sys.core.cache.RedisCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 图片验证码控制类
 *
 * @author zhushengjie
 * @date 2022-09-14
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class SysCaptchaController {

    private final RedisCache redisCache;

    @Autowired
    private RedisBackCache redisBackCache;

    /**
     * 验证码长度
     */
    private final int DEFAULT_WIDTH = 120;

    /**
     * 验证码宽度
     */
    private final int DEFAULT_HEIGHT = 40;

    @GetMapping("/captcha.jpg")
    public void generateCaptcha(HttpServletResponse response) {
        try {
            RandomGenerator randomGenerator = new RandomGenerator("0123456789",4);
            LineCaptcha captcha = CaptchaUtil.createLineCaptcha(DEFAULT_WIDTH,DEFAULT_HEIGHT,4,80);
            captcha.setGenerator(randomGenerator);
            captcha.createCode();

            HttpServletRequest request = HttpServletUtil.getRequest();
            String ip = "";
            if (ObjectUtil.isNotNull(request)) {
                ip = IpAddressUtil.getIp(request);
            }

            String redisCaptchaKey = CommonConstant.CAPTCHA_CODE + "_" + ip;
            //获取验证码信息
            String text = captcha.getCode();
            //验证码放入redis缓存
            redisCache.put(redisCaptchaKey, text, CommonConstant.CAPTCHA_CODE_EXP_TIME);
            redisBackCache.put(redisCaptchaKey, text, 10*60);
            response.setContentType("image/jpeg");
            captcha.write(response.getOutputStream());
        } catch (Exception e) {
            log.error(">>> 图片验证码生成异常: " + e);
        }
    }
}
